<template>
  <!-- 员工情况列表 -->
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="60px"
        >
          <el-form-item label="账号" prop="phoneNumber">
            <el-input
              v-input-restrict
              v-model="queryParams.phoneNumber"
              placeholder="请输入账号"
              clearable
              style="width: 200px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input
              v-input-restrict
              v-model="queryParams.name"
              placeholder="请输入姓名"
              clearable
              style="width: 200px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="岗位" prop="postIds">
            <el-select
              v-model="queryParams.postIds"
              placeholder="岗位"
              filterable
              style="width: 200px"
            >
              <el-option label="全部" :value="undefined" />
              <el-option
                v-for="dict in postOptions"
                :key="dict.postId"
                :label="dict.postName"
                :value="dict.postId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="状态"
              style="width: 200px"
            >
              <el-option label="全部" :value="undefined" />
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              v-preventReClick
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button
              v-preventReClick
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-preventReClick
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-upload
              multiple
              :http-request="handleImport"
              :show-file-list="false"
              action="#"
              accept=".xls,.xlsx"
              ref="upload"
            >
              <el-button
                v-preventReClick
                type="warning"
                plain
                icon="el-icon-folder-add"
                size="mini"
                >导入</el-button
              >
            </el-upload>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-preventReClick
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              >导出</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-preventReClick
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleTemplate"
              >下载模板</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList">
          <el-table-column label="" align="center" prop="" width="40">
            <template slot-scope="scope">
              <img v-if="scope.row.isSchoolManager==1" style="width:20px;height: auto;" src="@/assets/images/5.png" alt="" />
            </template>
          </el-table-column>
          <el-table-column
            label="姓名"
            align="center"
            prop="nickName"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column label="账号" align="center" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.phoneNumber | regPhone }}</span>
            </template>
          </el-table-column>
          <el-table-column label="性别" align="center" prop="sex">
            <template slot-scope="scope">
              <span>{{
                scope.row.sex == 0 ? "男" : scope.row.sex == 1 ? "女" : ""
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="岗位"
            align="center"
            prop="postNames"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column width="70" label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_normal_disable"
                :value="scope.row.status"
              />
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="240"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                v-hasPermi="['system:user:userDetail']"
                v-preventReClick
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleDetail(scope.row)"
                >详情</el-button
              >
              <el-button
                v-preventReClick
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                >编辑</el-button
              >
              <el-button
                v-preventReClick
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleReset(scope.row)"
                >重置密码</el-button
              >
              <!-- <el-button
                v-preventReClick
                size="mini"
                type="text"
                icon="el-icon-open"
                @click="handleDisable(scope.row)"
                >{{ scope.row.status == "0" ? "停用" : "启用" }}</el-button
              > -->

              <el-button
                v-preventReClick
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                >移除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <addUserDialog
      :shopObject="info"
      from="user"
      :id="addUserId"
      :open.sync="addUserOpen"
      :type="addUserType"
      @refresh="getList()"
    ></addUserDialog>
    <importError
      :open.sync="importErrorOpen"
      :list="importErrorList"
      :tip="importErrorTip"
    ></importError>
  </div>
</template>
  
  <script>
import addUserDialog from "@/components/addUser";
import uploadAvatar from "@/components/uploadAvatar";
import importError from "@/components/importError";
import { changeUserStatus } from "@/api/system/user";
import { listPost_school } from "@/api/school/list";
import { listPost } from "@/api/system/post";
import {
  listPost_student,
  unbindStudent,
  updatePost_student,
  import_student,
  addPost_resetPwd,
} from "@/api/schoolOrganization/student";
export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { uploadAvatar, addUserDialog, importError },
  props: {
    // 传入整个门店信息 用于新增的时候传入 新增组件
    info: {
      type: Object,
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 岗位选项
      postOptions: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phoneNumber: undefined,
        name: undefined,
        status: undefined,
        schoolIds: undefined,
        postIds: undefined,
      },

      // 角色列表
      addUserOpen: false,
      addUserType: 1,
      addUserId: undefined,
      // 导入失败组件参数
      importErrorOpen: false,
      importErrorList: [],
      importErrorTip: "",
    };
  },
  watch: {
    info(e) {
      this.getList();
    },
  },
  created() {
    this.getPostList();
  },

  methods: {
    /* 获取岗位 */
    getPostList() {
      listPost({
        pageNum: 1,
        pageSize: 9999,
      }).then((response) => {
        this.postOptions = response.rows;
      });
    },
    /* 详情 */
    async handleDetail(row) {
      // 跳转员工详情页面
      this.$router.push({
        path: "/system/userDetail",
        query: {
          studentId: row.studentId,
          userId: row.userId,
          from: "shop",
        },
      });
    },
    /* 重置密码 */
    handleReset(row) {
      this.$confirm(
        "是否确认重置密码？重置后密码为：ZYsd+手机号后六位，例如：ZYsd123456",
        "重置密码确认 ",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          addPost_resetPwd(row.userId).then((response) => {
            this.$message({
              message: "重置成功",
              type: "success",
            });
          });
        })
        .catch();
    },
    /* 停用启用 */
    handleDisable(row) {
      console.log(row);
      this.$confirm(
        `是否确认${row.status == "0" ? "停用" : "启用"}【${row.name}】吗?${
          row.status == "0" ? "停用后该账号不可登录使用！" : ""
        }`,
        `${row.status == "0" ? "停用提示" : "启用提示"}`,
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let data = JSON.parse(JSON.stringify(row));
          data.status = row.status == "0" ? "1" : "0";
          updatePost_student(data).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.getList();
          });
        })
        .catch(() => {});
    },
    /* 下载模板 */
    handleTemplate() {
      window.location.href = "/static/student_import_template.xlsx";
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      let queryParams = { ...this.queryParams };
      queryParams.schoolIds = this.info.schoolId;
      listPost_student(queryParams).then((response) => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addUserOpen = true;
      this.addUserType = 1;
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      console.log(row);
      this.addUserId = row.studentId;
      this.addUserOpen = true;
      this.addUserType = 2;
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      let schoolIds = row.schoolIds.split(",");
      console.log(schoolIds);
      let txt;
      if (schoolIds.length == 1) {
        txt = `【${row.name}】账号只有一个门店,无法移除,确定将【${row.name}】移除吗？删除后不可恢复！`;
      } else {
        txt = `确定将【${row.name}】账号移除【${this.info.schoolName}】吗？移除后不可恢复！`;
      }
      this.$confirm(txt, `移除确认`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            let res = await unbindStudent(this.info.schoolId, userIds);
            if (res.code == 200) {
              this.getList();
              this.$modal.msgSuccess("移除成功");
            }
          } catch (error) {}
        })
        .catch(() => {});
    },
    /* 导入操作 */
    async handleImport(file) {
      let formData = new FormData();
      formData.append("schoolId", this.info.schoolId);
      formData.append("file", file.file);
      const loading = this.$loading({
        lock: true,
        text: "正在上传,请稍等…",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      import_student(formData)
        .then((response) => {
          loading.close();
          this.getList();
          if (response.data) {
            this.importErrorTip = response.msg;
            this.importErrorList = response.data;
            this.importErrorOpen = true;
          } else {
            this.$modal.msgSuccess(response.msg);
          }
        })
        .catch((err) => {
          loading.close();
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      let params = { ...this.queryParams };
      params.schoolIds = this.$route.query.shopId;
      this.download(
        "/manager/account/student/export",
        {
          ...params,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
  